package demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class HttpRequest {
	
    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7",
            "8", "9", "a", "b", "c", "d", "e", "f"};
    public final static String APP_KEY = "1512970442";
    public final static String APP_SECRET = "15129704425138";

	public static String mapToString(Map<String, String> paramMap) {
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> entry : paramMap.entrySet()) {
			sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
		}
		return sb.toString();
	}

	public static String getSign(Map<String, String> signParam) {
		String joinStr = toJoinStrASCII(signParam, false, false);
		String result = MD5Encode(APP_SECRET.concat(joinStr).concat(APP_SECRET)).toUpperCase();
		return result;
	}

    public static String MD5Encode(String origin) {
        String resultString = null;
        try {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(resultString.getBytes("UTF-8"));
            resultString = byteArrayToHexString(md.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }

    public static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte aB : b) {
            resultSb.append(byteToHexString(aB));
        }
        return resultSb.toString();
    }
    
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
    
	public static String toJoinStrASCII(Map<String, String> map, boolean encoder, boolean lowerCase) {
		map.remove("app_sign");
		Map<String, String> tmpMap = map;
		List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
		Collections.sort(infoIds, new DemoCompare());
		StringBuilder sb = new StringBuilder();
		try {
			if (encoder && lowerCase) {
				for (Map.Entry<String, String> entry : infoIds) {
					if (isBlank(entry.getKey()) || isBlank(entry.getValue())) {
						continue;
					}
					sb.append(entry.getKey().toLowerCase()).append(URLEncoder.encode(entry.getValue(), "UTF-8"));
				}
			} else if (encoder) {
				for (Map.Entry<String, String> entry : infoIds) {
					if (isBlank(entry.getKey()) || isBlank(entry.getValue())) {
						continue;
					}
					sb.append(entry.getKey()).append(URLEncoder.encode(entry.getValue(), "UTF-8"));
				}
			} else if (lowerCase) {
				for (Map.Entry<String, String> entry : infoIds) {
					if (isBlank(entry.getKey()) || isBlank(entry.getValue())) {
						continue;
					}
					sb.append(entry.getKey().toLowerCase()).append(entry.getValue());
				}
			} else {
				for (Map.Entry<String, String> entry : infoIds) {
					if (isBlank(entry.getKey()) || isBlank(entry.getValue())) {
						continue;
					}
					sb.append(entry.getKey()).append(entry.getValue());
				}
			}
		} catch (UnsupportedEncodingException e) {
			;
		}
		return sb.toString();
	}

    private static boolean isBlank(String key) {
		return key == null || key.equals("");
	}

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("Send POST Error!"+e);
            e.printStackTrace();
        }
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
}
